package com.codegenerate.demo.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.codegenerate.demo.config.R;
import com.codegenerate.demo.dto.AppFunDto;
import com.codegenerate.demo.dto.LoginDto;
import com.codegenerate.demo.entity.AppFun;
import com.codegenerate.demo.entity.SysAccount;
import com.codegenerate.demo.service.AppFunService;
import com.codegenerate.demo.service.AuthService;
import com.codegenerate.demo.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/auth")
public class AuthController {
    @Autowired
    AuthService authService;
    @Autowired
    AppFunService appFunService;


    @PostMapping("/login")
    public R<LoginDto> login(@RequestBody LoginDto  loginDto){
        // region 校验
        if(StringUtils.isEmpty(loginDto.getUserName())) {
           return  R.failed("username 参数");
        }
        if(StringUtils.isEmpty(loginDto.getPassWord())) {
            return  R.failed("password 参数");
        }
            // endregion
        // region  登录后 得到token
        var result = authService.login(loginDto);
        // endregion
        return result;
    }


    @GetMapping("/user/getuserinfobyauth")
    public R<SysAccount> parseToken(@RequestHeader("Authorization")String authorizationStr){
        var token = authorizationStr.split("Bearer ")[1];
        if(StringUtils.isEmpty(token)){
            return R.failed("没有token");
        }
        return authService.parseToken(token);
    }

    @PostMapping("/getmenu")
    public R<List<AppFun>> getmenu(@RequestBody AppFunDto appFunDto){
        var query=appFunDto.dto2entity().getQueryAll();
        Page<AppFun> page = appFunService.page(
                new Page<AppFun>(1,500),query
        );
        var list=page.getRecords();
        for (int i = 0; i <list.size() ; i++) {
            var one = list.get(i);
            one.setHaveNext(appFunService.exitHaveNext(one.getId()));
        }
        return R.ok(list)
                .setCount(page.getTotal());
    }
}


